package net.grzechocinski.wordcounter.core;

import net.grzechocinski.wordcounter.KMP.KMP;
import net.grzechocinski.wordcounter.KMP.WordObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mateusz
 * @since 2010-05-09
 */
public class WordCounter {

	private static Logger log = org.slf4j.LoggerFactory.getLogger(WordCounter.class);

	public static List<WordObject> analyze(String toAnalyze) {

		final Map<String, WordObject> tokenOccurrences = countAloneOccurances(toAnalyze);

		List<WordObject> wordObjects = new ArrayList<WordObject>(tokenOccurrences.values());
		KMP.countInOtherOccurrences(wordObjects);

		log.info("List: {}", wordObjects);
		return wordObjects;
	}

	private static Map<String, WordObject> countAloneOccurances(String toAnalyze) {
		final Map<String, WordObject> tokenOccurances = new HashMap<String, WordObject>();
		final String[] tokens = toAnalyze.split("\\s");

		for (String token : tokens) {

			if (StringUtils.isBlank(token)) {
				continue;
			}

			log.info("Analyzing token '{}'", token);
			if (tokenOccurances.containsKey(token)) {
				tokenOccurances.get(token).incrementAloneCounter();
				//log.info("Incrementing counter of {} to {}", token, tokenOccurances.get(token).getAloneCounter());
			} else {
				tokenOccurances.put(token, new WordObject(token));
				//log.info("Put new object of {}", token);
			}
		}
		return tokenOccurances;
	}
}
